# -*- coding: utf-8 -*-
# created on 2016/12/20

from sympy import sympify, Mul, Intersection
from sympy.core.function import UndefinedFunction

from mathsolver.functions.base import BaseFunction, BaseIneq, BaseBelong, new_latex
from mathsolver.functions.budengshi.jiebudengshi import JieBuDengShi
from mathsolver.functions.hanshu.helper import yizhizhiyu_qiufanwei, reverse_op


class DanDiaoBuDengShi(BaseFunction):
    """函数单调性得不等式（组）"""

    def solver(self, *args):
        qujian, dandiao, ineq = args

        # ineq 化简成 f(g(a)) op f(h(a)) 的格式
        left, op, right = ineq.value
        left = sympify(left)
        right = sympify(right)

        if isinstance(left.func, UndefinedFunction) and isinstance(right.func, UndefinedFunction):
            pass
        else:
            if right == 0:
                neg_arg = [arg for arg in left.args if arg.func == Mul][0]
            elif left == 0:
                neg_arg = [arg for arg in right.args if arg.func == Mul][0]
            else:
                raise ValueError('unknown type %s' % ' '.join([str(left), op, str(right)]))

            left = left - neg_arg
            right = right - neg_arg
            self.steps.append(["", "将不等式转换为 %s" % ' '.join([str(left), op, str(right)])])

        ga, ha = left.args[0], right.args[0]

        if '增' in dandiao:
            res = [ga, op, ha]
        else:
            res = [ga, reverse_op(op), ha]

        self.steps.append(["", "由题意可知： %s, %s ∈ %s, %s ∈ %s" % (' '.join([str(item) for item in res]), new_latex(ga), new_latex(qujian), new_latex(ha), new_latex(qujian))])

        self.output.extend([BaseIneq(res), BaseBelong([ga, '\\in', qujian]), BaseBelong([ha, '\\in', qujian])])
        self.label.add("函数单调性得不等式（组）")
        return self


# hs051.元素属于区间求参数
belong_qujian_qiucan = yizhizhiyu_qiufanwei


class DanDiaoJieBuDengShi(BaseFunction):
    """函数单调性解不等式"""

    def solver(self, *args):
        # 函数单调性得不等式
        get_budengshi_step = DanDiaoBuDengShi().solver(*args)
        self.steps.extend(get_budengshi_step.steps)
        ineq, belong1, belong2 = get_budengshi_step.output

        # 元素属于区间求参数
        ga, _, dd1 = belong1.value
        ha, _, dd2 = belong2.value
        qujian1 = belong_qujian_qiucan(sympify(ga), dd1)
        qujian2 = belong_qujian_qiucan(sympify(ha), dd2)

        # 解不等式
        res_ineq = JieBuDengShi().solver(ineq).output[0].value.values()[0]
        res = Intersection(qujian1, qujian2, res_ineq)
        self.steps.append(["", "所以取值范围为 %s" % new_latex(res)])
        self.output.append(res)
        self.label.add("函数单调性解不等式")
        return self


if __name__ == '__main__':
    pass
